#include "coordinator.h"
#include <QNetworkProxy>
#include "httpclient.h"
#include <QTime>

Coordinator::Coordinator(QObject *parent) :
    QObject(parent)
{
    trigger();
    coordTimer.setInterval(20000);
    connect(&coordTimer, SIGNAL(timeout()), this, SLOT(trigger()));
    coordTimer.start();
}

void Coordinator::trigger(){

    QVector<Link*> availLinks=f.getAvailLinks();
    foreach(Link* link, availLinks){
        ProxyDesc* proxy=p.getProxyFor(link->hostService());
        if(proxy!=NULL){
            //download
            link->setState(Link::INUSE);
            link->setProxy(proxy);
            qDebug()<<"Will download"<<proxy->port()<<link->url().toString();
            link->setClient(new HttpClient());
            connect(link->client(),SIGNAL(finnished(Link*)),this, SLOT(finnishedHandler(Link*)));
            connect(link->client(),SIGNAL(wait(int,Link*)),this, SLOT(waitHandler(int,Link*)));
            connect(link->client(),SIGNAL(error(int,Link*)),this, SLOT(errorHandler(int, Link*)));
            link->client()->setAddress(link);
        }

    }
}
void Coordinator::waitHandler(int sec,Link* link){
    //link->setWaitUntil(QTime::currentTime().addSecs(sec));
    link->proxy()->wait(link->hostService(),QTime::currentTime().addSecs(sec));
    p.returnProxy(link->proxy());
    link->setState(Link::FREE);
    link->setProxy(NULL);
    delete link->client();
};

void Coordinator::finnishedHandler(Link* link){
    link->setState(Link::FINISHED);
    p.returnProxy(link->proxy());
    link->setProxy(NULL);
    delete link->client();
};

void Coordinator::errorHandler(int errCode,Link* link){
    qDebug()<< __FILE__<<":"<<__LINE__<<"\t"<<"File:"<<link->url()<<"some issue"<<errCode<<"status was"<<link->state();
    link->setState(errCode);
    qDebug()<< __FILE__<<":"<<__LINE__<<"\t"<<"File:"<<link->url()<<"some issue"<<errCode<<"status is"<<link->state();
    p.returnProxy(link->proxy());
    link->setProxy(NULL);
    delete link->client();
};


